'use strict';

var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');

var userSchema = new mongoose.Schema({
    email: {
        type: String,
        unique: true
    },
    username: {
        type: String,
        unique: true
    },
    password: {
        type: String
    },
    avator: {
        type: String,
        default: './assets/avators/default.png'
    },
    phone: {
        type: Number,
        unique: true
    },
    score:{
        type: Number,
        default: 0
    },
    sign:{
        type: String,
        default: ''
    },
    token: {
        type: String,
        default: ''
    }
})

//为实体userEntity创建保存方法
userSchema.pre('save', function(next) {
    var user = this;
    if (!user.isModified('password')) {
        return next();
    }
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(user.password, salt, function(err, hash) {
            user.password = hash;
            next();
        });
    });
});

//为模型schema创建对比密码的方法
userSchema.methods.comparePassword = function(password, done) {
    bcrypt.compare(password, this.password, function(err, isMatch) {
        done(err, isMatch);
    });
}

module.exports = mongoose.model('User', userSchema);
